package com.chaoxin.lovehelp.controller;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.*;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chaoxin.lovehelp.common.enums.ErrorCode;
import com.chaoxin.lovehelp.common.enums.vo.ResetPasswordVo;
import com.chaoxin.lovehelp.common.exception.BusinessException;
import com.chaoxin.lovehelp.common.validator.IdCardCheck;
import com.chaoxin.lovehelp.common.enums.SystemEnum;
import com.chaoxin.lovehelp.common.enums.vo.allFellowVo;
import com.chaoxin.lovehelp.common.enums.vo.fellowRegisterVo;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import com.chaoxin.lovehelp.entity.FellowEntity;
import com.chaoxin.lovehelp.service.FellowService;
import com.chaoxin.lovehelp.common.utils.PageUtils;
import com.chaoxin.lovehelp.common.utils.R;

import javax.servlet.http.HttpServletRequest;



/**
 * 
 *
 * @author honghu
 * @email 3027708213@qq.com
 * @date 2024-02-04 22:13:14
 */
@RestController
@CrossOrigin
@RequestMapping("lovehelp/fellow")
public class FellowController {
    @Autowired
    private FellowService fellowService;

    /**
     * 登录功能
     */
    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> loginInfo, HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        System.out.println("开始登陆");
        String tel = loginInfo.get("tel");
        String password = loginInfo.get("password");

        if (fellowService.authenticate(tel,  password,request)) {
            System.out.println("登录成功");
            return R.ok();
        }else {
            return R.error(401,  "未注册或密码错误");
        }
    }


    @GetMapping("get/login")
    public R getLogin(HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        FellowEntity fellowServiceLogin = fellowService.getLogin(request);
        if (fellowServiceLogin==null)return R.error(ErrorCode.NOT_LOGIN_ERROR.getCode(),"未登录");
        allFellowVo allFellowVo = new allFellowVo();
        BeanUtils.copyProperties(allFellowVo,fellowServiceLogin);

        return R.ok().setData(allFellowVo);
    }

    @PostMapping("/register")
    public R register(@RequestBody fellowRegisterVo fellow) throws ParseException {
        QueryWrapper<FellowEntity> wrapper = new QueryWrapper<>();

        IdCardCheck cardCheck = new IdCardCheck();
        //根据生日计算年龄
        if (fellow.getBirthTime() != null) {
            fellow.setAge(getAgeByBirth(fellow.getBirthTime()));
        }
        if (!StringUtils.isEmpty(fellow.getIdentityId())) {
            //身份证号校验
            if (!cardCheck.checkIdCardNum(fellow.getIdentityId())) {
                return R.error(400, "请输入正确的身份证号。");
            }
            //检查电话是否重复
            wrapper.eq("tel", fellow.getTel());
            List<FellowEntity> list1 = fellowService.list(wrapper);
            if (!CollectionUtils.isEmpty(list1)) {

                return R.error(500, "该电话已经注册");
            }
            //查询身份证号在数据库中是否存在
            wrapper.eq("is_display", 1).eq("identity_id", fellow.getIdentityId());
            List<FellowEntity> list = fellowService.list(wrapper);
            if (!CollectionUtils.isEmpty(list)) {

                return R.error(500, "该会员已存在");
            }
            if (!StringUtils.isEmpty(fellow.getConfirmPassword())){
                return R.error("确认密码不能为空");
            }
            if(fellow.getPassword().equals(fellow.getConfirmPassword())==false)
                return R.error("两次密码输入不一致");
        }
        if(cardCheck.checkTel(fellow.getTel())){

            fellow.setIsDisplay(1);

            fellowService.save(fellow);

            return R.ok();
        }
        return R.error(500,"请输入正确的电话号。");
    }





    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,HttpServletRequest request){
//        FellowEntity loginUser =(FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        PageUtils page = fellowService.queryPage(request,params);
        return R.ok().put("page", page);

//        return R.error(403,"您的角色为普通用户，无权限查询");



    }


    /**
     * 单个会员信息,查询个人信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
        FellowEntity fellow  = fellowService.getById(id);
        fellowService.transferAllFellowVo(fellow);

        return R.ok().put("fellowVo",fellowService.transferAllFellowVo(fellow));
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody FellowEntity fellow,HttpServletRequest request) throws ParseException {
        QueryWrapper<FellowEntity> wrapper = new QueryWrapper<>();

        IdCardCheck cardCheck = new IdCardCheck();
        //根据生日计算年龄
        if(fellow.getBirthTime()!=null){
            fellow.setAge(getAgeByBirth(fellow.getBirthTime()));
        }
        if(!StringUtils.isEmpty(fellow.getIdentityId())){
            //身份证号校验
            if(!cardCheck.checkIdCardNum(fellow.getIdentityId())){
                return R.error(400,"请输入正确的身份证号。");
            }
            //检查电话是否重复
            wrapper.eq("tel",fellow.getTel());
            List<FellowEntity> list1 = fellowService.list(wrapper);
            if(!CollectionUtils.isEmpty(list1)){

                return R.error(500,"该电话已经注册");
            }
            //查询身份证号在数据库中是否存在
            wrapper.eq("is_display",1).eq("identity_id",fellow.getIdentityId());
            List<FellowEntity> list = fellowService.list(wrapper);
            if(!CollectionUtils.isEmpty(list)){

                return R.error(500,"该会员已存在");
            }
        }
        //电话号校验
        if(cardCheck.checkTel(fellow.getTel())){

            fellow.setIsDisplay(1);

            fellowService.save(fellow);

            return R.ok();
        }return R.error(400,"请输入正确的电话号。");

    }

    /**
     * 修改个人信息，（管理员可以修改全部信息，普通用户只能修改本人信息）
     */
    @PostMapping("/update")
    public R update(@RequestBody FellowEntity fellow,HttpServletRequest request) throws ParseException {
        FellowEntity loginUser =(FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        if (loginUser.getId()==fellow.getId() || loginUser.getRole()==1 || loginUser.getRole()==2){//管理员或者自己可以修改信息
            IdCardCheck cardCheck = new IdCardCheck();
            //根据生日计算年龄
            if(fellow.getBirthTime()!=null){
                fellow.setAge(getAgeByBirth(fellow.getBirthTime()));
            }
            if(!StringUtils.isEmpty(fellow.getIdentityId())){
                //身份证号校验
                if(!cardCheck.checkIdCardNum(fellow.getIdentityId())){
                    return R.error(400,"请输入正确的身份证号。");
                }
            }
            //电话号校验
            if(cardCheck.checkTel(fellow.getTel())){
                fellowService.updateById(fellow);
                return R.ok();
            }
            return R.error(400,"请输入正确的电话号。");
        }else {
            return R.error(403,"无权限修改请联系管理员");
        }

    }
    /**
     * 传入会员id根据设置用户角色
     */
    @PostMapping("/setRole/{id}/{roleId}")
    public R updateRole(@PathVariable("id") Integer id,@PathVariable("roleId") Integer roleId,HttpServletRequest request){
        FellowEntity loginUser =(FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        //防止超级管理员操作自己状态
        if (id==1 && loginUser.getRole()==1)return R.error("您已经是超级管理员，无法修改角色");
        if(loginUser.getRole()==1){//超级管理员才能设置其他人的状态
            Boolean b = fellowService.setRole(id, roleId);
            if (b)return R.ok("设置成功");
        }
        return R.error("请联系超级管理员设置角色");

    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
		fellowService.removeIds(Arrays.asList(ids));

        return R.ok();
    }
    //获取所有会员信息（下拉框）
    @RequestMapping("/allFellowInfo")
    public R getAllFellow(HttpServletRequest request){
        FellowEntity loginUser =(FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());

        if(loginUser.getRole()==1 || loginUser.getRole()==2){//超级管理员才能设置其他人的状态
            List<allFellowVo> vos = fellowService.getAllFellow();
            return R.ok().put("fellowVoInfo",vos);
        }
        return R.error("非管理员无法访问这个接口");

    }

    //获取普通会员信息
    @RequestMapping("/getuserfellow")
    public R getUserFellow(HttpServletRequest request){
        FellowEntity loginUser =(FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());

        if(loginUser.getRole()==1 || loginUser.getRole()==2){//超级管理员才能设置其他人的状态
            List<allFellowVo> vos = fellowService.getUserFellow();
            return R.ok().put("fellowVoInfo",vos);
        }
        return R.error("非管理员无法访问这个接口");

    }

    //用户登出
    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        if (request==null)throw new BusinessException(ErrorCode.PARAMS_ERROR);
        boolean r=fellowService.userLogout(request);
        return R.ok();

    }

    /*
    重置密码
     */
    @PostMapping("/resetPassword")
    public R resetPassword(@RequestBody ResetPasswordVo resetPasswordVo,HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        //登录用户必须超级管理员
        FellowEntity loginUser =(FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        if (loginUser.getRole()!=1)throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"您无权限修改密码");
        fellowService.resetPassword(resetPasswordVo.getId(),resetPasswordVo.getPassword());
        return R.ok();
    }


    //计算年龄
    private static int getAgeByBirth(Date birthday) {
        int age = 0;
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间

            Calendar birth = Calendar.getInstance();
            birth.setTime(birthday);

            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//兼容性更强,异常后返回数据
            return 0;
        }
    }

}
